import os, sys
from ftplib import FTP

release_dir = '/pub/I9200_Release/release'
download_path = './'

args = len(sys.argv)
if args >= 2:
    download_path = sys.argv[1]
    
class MyFTP(FTP):
    def __init__(self):    
        self.ftp = FTP().__init__()
        self.i9200_dir = ''
        self.i9200_file = ''
        self.download_file = ''
        
    def loginFtp(self):
        self.ftp = FTP('165.213.149.206')
        self.ftp.login('lin.yuan', 'lin.yuan')
        print "Begin here---------->"
        
    def getDirFile(self):
        self.i9200_dir = self.ftp.nlst(release_dir)[len(self.ftp.nlst(release_dir)) - 1]
        for item in self.ftp.nlst(self.i9200_dir):
            if 'I9200' in item and 'ubi.tar' in item:
                self.i9200_file = item.split('/')[-1]
    
    def checkExist(self, path):
        self.download_file = os.path.join(path, self.i9200_file)
        if os.path.isfile(self.download_file):
            return True
        else:
            return False
                
    def downloadFile(self):
        self.ftp.cwd(self.i9200_dir)
        print "Download %s from %s to %s" % (self.i9200_file, self.i9200_dir, self.download_file)    
        self.ftp.retrbinary('RETR %s' % self.i9200_file, open(self.download_file, 'wb').write)
    
    def quitFtp(self):
        print "End here------------>"
        self.ftp.quit()        

def main():
    ftp = MyFTP()
    ftp.loginFtp()
    ftp.getDirFile()
    if not ftp.checkExist(download_path):
        ftp.downloadFile()
    else:
        print "You have got the latest version!"
    ftp.quitFtp()
        
if __name__ == '__main__':
    main()